var initAudio = function(audio, options) {
	var A= new AUI();
	
	if(audio.length == 0) {
		if(Window['console']) console.error('audio is not defined');
		return;
	}
	
	////var popcorn = Popcorn("#video-content");
	
	//var audio=document.getElementById('audio-beat');
	var audio = audio.get(0);
//	console.log(audio);
	audio.src=audioLink;
//	console.log('audioLink: '+ audioLink);
	
//	var limit = audio.duration.toFixed(3);
		
	audio.addEventListener("play", function() {
//		limit = audio.duration;
//		console.log("limit: " + limit);
//		limit= limit.toFixed(3);
//		console.log('-->audio');
//		console.log("limit: " + limit);
		// popcorn.play();
		audio_play();
	
	}, false);
	
	function audio_play() {
		karaokeShow.reset();
		var currentTime = audio.currentTime;
//		console.log("currentTime: " + currentTime);
		karaokeShow.render(currentTime);
	
		interval = setInterval(function() {
//			if (currentTime > limit) {
//				clearInterval(interval);
//			}
			currentTime += rate;
			karaokeShow.render(currentTime.toFixed(3));
		}, rate * 1000);
	};
	
	audio.addEventListener("pause", function() {
		console.log('audio pause');
		karaokeShow.reset();
		clearInterval(interval);
	}, false);
	
	audio.addEventListener("seeking", function(){
		clearInterval(interval);
	}, false);
	
	audio.addEventListener("ended", function(){
		clearInterval(interval);
		myStopFunction();
		if(isRecoding)
			showPopup();
	}, false);
	
	
	audio.addEventListener("seeked", function() {
		if (!audio.paused) {
			audio_play();
		}
	}, false);
	
	
	
	function playPauseClick() {
		audio.play();
	}
	
	/* recoding */
	//variables
	var leftchannel = [];
	var rightchannel = [];
	var recorder = null;
	var recording = false;
	var recordingLength = 0;
	var volume = null;
	var audioInput = null;
	var sampleRate = 11025;
	var audioContext = null;
	var context = null;
	var outputElement = document.getElementById('output');
	var outputString;
	var recordingUrl;
	var blob;
	/* When recording click */
	function recordingFuction() {
		// feature detection
		if (!navigator.getUserMedia)
			navigator.getUserMedia = navigator.getUserMedia
					|| navigator.webkitGetUserMedia || navigator.mozGetUserMedia
					|| navigator.msGetUserMedia;
	
		if (navigator.getUserMedia) {
			navigator.getUserMedia({
				audio : true
			}, success, function(e) {
				alert('Error capturing audio...');
			});
		} else
			alert('getUserMedia not supported in this browser.');
	}
	
	//function confirmRecoding(e){
	//var confirm= confirm("Recording?");
	//if(confirm){
	//success(e);
	//recording = true;
	//// reset the buffers for the new recording
	//leftchannel.length = rightchannel.length = 0;
	//recordingLength = 0;
	//// outputElement.innerHTML = 'Recording now...';
	//}
	//}
	
	function myStopFunction() {
		console.log('stop recording ...');
		// we stop recording
		recording = false;
	
		// outputElement.innerHTML = 'Building wav file...';
	
		// we flat the left and right channels down
		var leftBuffer = mergeBuffers(leftchannel, recordingLength);
	//	var rightBuffer = mergeBuffers(rightchannel, recordingLength);
		// we interleave both channels together
		var interleaved = interleave(leftBuffer);
	
		// we create our wav file
		var buffer = new ArrayBuffer(44 + interleaved.length * 2);
		var view = new DataView(buffer);
	
		// RIFF chunk descriptor
		writeUTFBytes(view, 0, 'RIFF');
		view.setUint32(4, 44 + interleaved.length * 2, true);
		writeUTFBytes(view, 8, 'WAVE');
		// FMT sub-chunk
		writeUTFBytes(view, 12, 'fmt ');
		view.setUint32(16, 16, true);
		view.setUint16(20, 1, true);
		// stereo (2 channels)
		view.setUint16(22, 1, true);
		view.setUint32(24, sampleRate, true);
		view.setUint32(28, sampleRate * 4, true);
		view.setUint16(32, 4, true);
		view.setUint16(34, 16, true);
		// data sub-chunk
		writeUTFBytes(view, 36, 'data');
		view.setUint32(40, interleaved.length * 2, true);
	
		// write the PCM samples
		var lng = interleaved.length;
		var index = 44;
		var volume = 1;
		for (var i = 0; i < lng; i++) {
			view.setInt16(index, interleaved[i] * (0x7FFF * volume), true);
			index += 2;
		}
	
		// our final binary blob
		blob = new Blob([ view ], {
			type : 'audio/mp3'
		});
	
		// let's save it locally
		// outputElement.innerHTML = 'Handing off the file now...';
		/**
		 * 
		 */	
		recordingUrl = (window.URL || window.webkitURL).createObjectURL(blob);
	};
	
	/**
	 * nghe lai
	 */
	function playRecording() {
		var audioR = document.createElement('audio');
		audioR.src = recordingUrl;
		audioR.play();
		
		audioBeatReplay();
	};
	
	/**
	 * chay lai bai mp3
	 */
	function audioBeatReplay(){
		audio.load();
		audio.play();
	};
	
	function interleave(leftChannel) {
		var length = leftChannel.length / 4;
		var result = new Float32Array(length);
	
		var index = 0,
		  inputIndex = 0;
	
		while (index < length) {
		    result[index++] = 0.25 * (leftChannel[inputIndex++] + leftChannel[inputIndex++] +
		    		leftChannel[inputIndex++] + leftChannel[inputIndex++]);
		}
	
		return result;
	}
	
	function mergeBuffers(channelBuffer, recordingLength) {
		var result = new Float32Array(recordingLength);
		var offset = 0;
		var lng = channelBuffer.length;
		for (var i = 0; i < lng; i++) {
			var buffer = channelBuffer[i];
			result.set(buffer, offset);
			offset += buffer.length;
		}
		return result;
	}
	
	function writeUTFBytes(view, offset, string) {
		var lng = string.length;
		for (var i = 0; i < lng; i++) {
			view.setUint8(offset + i, string.charCodeAt(i));
		}
	}
	
	function success(e) {
		//play audio
		audio.load();
		$('#jp-play').trigger( "click" );
		isRecoding=true;
		
		//
		recording = true;
		// reset the buffers for the new recording
		leftchannel.length = rightchannel.length = 0;
		recordingLength = 0;
	
		// creates the audio context
		audioContext = window.AudioContext || window.webkitAudioContext;
		context = new audioContext();
	
		// creates a gain node
		volume = context.createGain();
	
		// creates an audio node from the microphone incoming stream
		audioInput = context.createMediaStreamSource(e);
	
		// connect the stream to the gain node
		audioInput.connect(volume);
	
		/*
		 * From the spec: This value controls how frequently the audioprocess event
		 * is dispatched and how many sample-frames need to be processed each call.
		 * Lower values for buffer size will result in a lower (better) latency.
		 * Higher values will be necessary to avoid audio breakup and glitches
		 */
		var bufferSize = 2048;
		recorder = context.createJavaScriptNode(bufferSize, 2, 2);
	
		recorder.onaudioprocess = function(e) {
			if (!recording)
				return;
			var left = e.inputBuffer.getChannelData(0);
	//		var right = e.inputBuffer.getChannelData(1);
			// we clone the samples
			leftchannel.push(new Float32Array(left));
	//		rightchannel.push(new Float32Array(right));
			
			recordingLength += bufferSize;
		};
	
		// we connect the recorder
		volume.connect(recorder);
		recorder.connect(context.destination);
	};
	
	/**
	 * luu bai thu
	 */
	function saveRecording() {
		console.log('resourceURL: '+ options.resourceURL);
		var fd = new FormData();
		fd.append('fname', options.songName);
		fd.append('data', blob);
		$.ajax({
		    type: 'POST',
		    url: options.resourceURL,
		    data: fd,
		    processData: false,
		    contentType: false
		}).done(function(data) {
		       data = 'var data=' + data;
		       eval(data);
		       console.log(data);
		       if(data.audioUrl) {
		    	   window.location = options.renderUrl;
		       }
		});
	};
	
		
	$('#jp-recording').click(function () {
		if(!isRecoding){
			clearInterval(interval);
			recordingFuction();
		}else{
			console.log('recording ....');
		}
				
//		showPopup();
	});
	
	/*
	 * Luu bai thu
	 */
	$(document).on('click', '#btn-save-record', function(){
		saveRecording();
	});
	
	/*
	 * nghe lai
	 */
	$(document).on('click', '#btn-re-play', function(){
		auiDialog.hide();
		$('#jp-play').trigger( "click" );
		
		var audioR = document.createElement('audio');
		audioR.src = recordingUrl;
		audioR.play();
		
	});
	
	/*
	 * Huy
	 */
	$(document).on('click', '#btn-cancel', function(){
		recordingUrl=null;
		blob=null;
		isRecoding=false;
		auiDialog.hide();
	});
	
	/*
	 * thu lai
	 */
	$(document).on('click', '#btn-re-record', function(){
		auiDialog.hide();
		//
		recordingUrl=null;
		blob=null;
		isRecoding=false;
		$('#jp-recording').trigger( "click" );
		
	});
	
//	$('#save-record').click(function(){
//		console.log("save recording");
////		saveRecording();
//	});
	
	$(document).on('click', '.jp-stop', function(){
		myStopFunction();
		if(audio.currentTime> 60){
			showPopup();
		}		
	});
	
	/**
	 * phat lai bai thu
	 */
	function playSanKhau(){
		
		var audioR = document.createElement('audio');
		audioR.src = recodringUrl;
		audioR.play();
		
		if(audio.currentTime>0){
			audio.load();
		}
		audio.muted=true;
		audio.play();
	};
	
	
	
	var popupContent=' <div>'+
		'<button id="btn-save-record" class"auiPopupBtn" style="width: 100%;">Lưu bài thu</button>'+ '<br>' +	
		'<button id="btn-re-play" class"auiPopupBtn" style="width: 100%;">Nghe lại</button>'+'<br>' +
		'<button id="btn-cancel" class"auiPopupBtn" style="width: 100%;">Hủy</button>'+'<br>' +
		'<button id="btn-re-record" class"auiPopupBtn" style="width: 100%;">Thu lại</button></div>';
	var auiDialog;
	function showPopup(){		
		AUI().ready('aui-dialog', 'aui-overlay-manager',
				'dd-constrain', function(A) {
				 auiDialog = new A.Dialog({
						title : 'Record',
						centered : true,
						modal : true,
						width : 300,
						height : 200,
						bodyContent : popupContent
					}).render();
		});
	};
	
	
};


var sanKhauAudio = function(audio, options) {
	if(audio.length == 0) {
		if(Window['console']) console.error('audio is not defined');
		return;
	}
	
	console.log('------------san khau------');
	console.log(recodingUrl);
	
	var audio = audio.get(0);
	audio.src=audioLink;
	
		
	audio.addEventListener("play", function() {
		limit = audio.duration;
		limit= limit.toFixed(3);
		audio_play();	
		
		console.log(recodingUrl);
		var audioR = document.createElement('audio');
		audioR.src = recodingUrl;
		audioR.play();
		
	}, false);
	
	function audio_play() {
		karaokeShow.reset();
		var currentTime = audio.currentTime;		
		karaokeShow.render(currentTime);
	
		interval = setInterval(function() {
			if (currentTime > limit) {
				clearInterval(interval);
			}
			currentTime += rate;
			karaokeShow.render(currentTime.toFixed(3));
		}, rate * 1000);
	};
	
	audio.addEventListener("ended", function(){
		clearInterval(interval);
	}, false);
	
	
	
};

AUI().ready(
		  'aui-tooltip',
		  function(A) {
		    new A.Tooltip(
		      {
		        title: true,
		        trigger: '#songTooltip'
		      }
		    ).render();
		  }
);